import React, { useEffect, useState, useRef } from 'react'
import {
  DownloadOutlined,
  GiftOutlined,
  PlusOutlined,
  ThunderboltOutlined,
  MoneyCollectOutlined,
  ShoppingOutlined,
  TeamOutlined
} from '@ant-design/icons'
import { regionData } from '../utils/region'
import {
  Button,
  Col,
  Flex,
  Form,
  Input,
  Row,
  Select,
  Typography,
  Table,
  Alert,
  Cascader,
  Switch,
  Modal,
  Divider,
  message
} from 'antd'
import MyDatePicker from '../components/MyDatePicker'
import { Link, useNavigate } from 'react-router-dom'
import { adminActivatyList, adminActivatyStatus } from '../service/activaty'

export default function MarketActivaty() {
  const navigate = useNavigate()
  // 保存选择的日期
  const [selectedDateString, setSelectedDateString] = useState(null)
  // 保存店铺列表
  const [storeList, setStoreList] = useState([])
  // 保存页码
  const [pageNo, setPageNo] = useState(1)
  // 总数据量
  const [total, setTotal] = useState(0)
  // 预设日期
  // 保存表格中选中的项
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  // 表格中是否有选中
  const hasSelected = selectedRowKeys.length > 0
  // 模态框
  const [isModalOpen, setIsModalOpen] = useState(false)
  // 获取省市区选中的值
  const regionChange = (value) => {
    console.log(value)
  }
  // 活动选项列表
  const activeList = [
    {
      index: 0,
      icon: <TeamOutlined />,
      title: '赠领'
    },
    {
      index: 1,
      icon: <ShoppingOutlined />,
      title: '拼团'
    },
    {
      index: 2,
      icon: <ThunderboltOutlined />,
      title: '秒杀'
    },
    {
      index: 3,
      icon: <MoneyCollectOutlined />,
      title: '返现'
    },
    {
      index: 4,
      icon: <GiftOutlined />,
      title: '抽奖'
    }
  ]
  // 默认选中的下标
  const [selectedIndex, setSelectedIndex] = useState(null)
  // 用于更新列表
  const [n, setN] = useState(1)
  const request = async () => {
    const res = await adminActivatyList({
      pageNo,
      pageSize: 10
    })
    console.log(res)
    if (res.data) {
      setStoreList(res.data.objects)
      setTotal(res.data.total)
    }
  }
  useEffect(() => {
    request()
  }, [n, pageNo])

  return (
    <>
      <Row className="info">
        <Col span={24}>
          <Flex justify={'space-between'}>
            <Typography.Title level={3}>信息管理</Typography.Title>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setIsModalOpen(true)}
            >
              新建活动
            </Button>
          </Flex>
        </Col>
      </Row>
      <Row className="container">
        <Col span={24}>
          <Form
            // layout="inline"
            onFinish={async (values) => {
              console.log(values)
              await request()
              setN(n + 1)
            }}
          >
            <Row>
              <Col span={6} className="myinput">
                <Form.Item label="活动标题：" name="storeName">
                  <Input placeholder="请输入活动标题" />
                </Form.Item>
              </Col>
              <Col span={6} className="myinput">
                <Form.Item label="活动类型：" name="storeHeadPhone">
                  <Select
                    placeholder="类型选择"
                    // style={{ width: 200 }}
                    options={[
                      {
                        value: '',
                        label: '全部'
                      },
                      {
                        value: '0',
                        label: '赠领'
                      },
                      {
                        value: '1',
                        label: '拼团'
                      },
                      {
                        value: '2',
                        label: '抽奖'
                      },
                      {
                        value: '3',
                        label: '砍一刀'
                      }
                    ]}
                  />
                </Form.Item>
              </Col>
              <Col span={6} className="myinput">
                <Form.Item label="活动渠道：" name="storeHeadPhone">
                  <Select
                    placeholder="渠道选择"
                    // style={{ width: 200 }}
                    options={[
                      {
                        value: '',
                        label: '全部'
                      },
                      {
                        value: '0',
                        label: 'APP'
                      }
                    ]}
                  />
                </Form.Item>
              </Col>
              <Col span={6} className="myinput">
                <Form.Item label="活动状态：" name="storeHeadPhone">
                  <Select
                    placeholder="请选择活动状态"
                    // style={{ width: 200 }}
                    options={[
                      {
                        value: '',
                        label: '全部'
                      },
                      {
                        value: '0',
                        label: '未开始'
                      },
                      {
                        value: '1',
                        label: '进行中'
                      },
                      {
                        value: '2',
                        label: '已结束'
                      }
                    ]}
                  />
                </Form.Item>
              </Col>
            </Row>
            <Row>
              <Col span={6} className="myinput">
                <Form.Item label="营销方式：" name="storeHeadPhone">
                  <Select
                    placeholder="请选择营销方式"
                    // style={{ width: 200 }}
                    options={[
                      {
                        value: '',
                        label: '全部'
                      },
                      {
                        value: '0',
                        label: '内容推送'
                      },
                      {
                        value: '1',
                        label: '消息推送'
                      }
                    ]}
                  />
                </Form.Item>
              </Col>
              <Col span={6} className="myinput">
                <Form.Item label="活动时间">
                  <MyDatePicker
                    selectedDateString={selectedDateString}
                    setSelectedDateString={setSelectedDateString}
                  />
                </Form.Item>
              </Col>
              <Col span={6} className="myinput">
                <Form.Item label="区域选择：" name="storeAddress">
                  <Cascader
                    options={regionData}
                    onChange={regionChange}
                    placeholder="请选择查询的省/市/区县"
                    style={{ width: 280 }}
                  />
                </Form.Item>
              </Col>
              <Col span={2} className="myinput">
                <Form.Item>
                  <Button type="default" htmlType="reset">
                    重置
                  </Button>
                </Form.Item>
              </Col>
              <Col span={1} className="myinput">
                <Form.Item>
                  <Button type="primary" htmlType="submit">
                    查询
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form>
        </Col>
      </Row>
      <Row className="container">
        <Col span={24}>
          <Typography.Paragraph style={{ fontSize: 16 }}>
            活动列表
          </Typography.Paragraph>
          {hasSelected && (
            <Alert
              message={`已经选择 ${selectedRowKeys.length} 项`}
              type="info"
              showIcon
            />
          )}
        </Col>
        <Col span={24}>
          <Table
            pagination={{
              total,
              defaultCurrent: 1,
              onChange: async (page) => {
                setPageNo(page)
              }
            }}
            rowKey="id"
            rowSelection={{
              selectedRowKeys,
              onChange: (newSelectedRowKeys) => {
                console.log('selectedRowKeys changed: ', newSelectedRowKeys)
                setSelectedRowKeys(newSelectedRowKeys)
              }
            }}
            dataSource={storeList}
            columns={[
              {
                title: '编号',
                dataIndex: 'id',
                key: 'id'
              },
              {
                title: '活动标题',
                dataIndex: 'activityName',
                key: 'activityName'
              },
              {
                title: '活动目标',
                dataIndex: 'activityTarget',
                key: 'activityTarget'
              },
              {
                title: '活动类型',
                dataIndex: 'activityType',
                key: 'activityType',
                render: (_, record) => {
                  return (
                    <>
                      {record.activityType === 1 && '赠领'}
                      {record.activityType === 2 && '拼团'}
                      {record.activityType === 3 && '抽奖'}
                      {record.activityType === 4 && '砍一刀'}
                    </>
                  )
                }
              },
              {
                title: '活动奖励',
                dataIndex: 'rewardCouponId',
                key: 'rewardCouponId'
              },
              {
                title: '店铺',
                dataIndex: 'shopIds',
                key: 'shopIds',
                render: (_, record) => {
                  // 获取店铺数量
                  return <>数量（{record.shopIds.split(',').length}）</>
                }
              },
              {
                title: '渠道',
                dataIndex: 'channelType',
                key: 'channelType',
                render: (_, record) => {
                  return (
                    <>
                      {record.channelType === 0 && '全部'}
                      {record.channelType === 1 && 'APP'}
                      {record.channelType === 2 && '小程序'}
                    </>
                  )
                }
              },
              {
                title: '营销方式',
                dataIndex: 'marketingType',
                key: 'marketingType',
                render: (_, record) => {
                  return (
                    <>
                      {record.marketingType === 0 && '全部'}
                      {record.marketingType === 1 && '内容推送'}
                      {record.marketingType === 2 && '消息推送'}
                    </>
                  )
                }
              },
              {
                title: '活动时间',
                dataIndex: 'storeStatus',
                key: 'storeStatus',
                render: (_, record) => {
                  return (
                    <>
                      {record.startDate} - {record.endDate}
                    </>
                  )
                }
              },
              {
                title: '活动状态',
                dataIndex: 'status',
                key: 'status',
                render: (_, record) => (
                  <Switch
                    defaultChecked={record.status === 1}
                    onChange={async (value) => {
                      console.log(value)
                      if (value) {
                        const res = await adminActivatyStatus({
                          id: record.id,
                          status: 1
                        })
                        console.log(res)
                        message.success('开启成功')
                      } else {
                        const res = await adminActivatyStatus({
                          id: record.id,
                          status: 0
                        })
                        console.log(res)
                        message.success('关闭成功')
                      }
                    }}
                  />
                )
              },
              {
                title: '操作',
                dataIndex: 'op',
                key: 'op',
                align: 'center',
                render: (_, record) => {
                  return (
                    <span className="op">
                      <Link to={`/admin/market/editActivaty/${record.id}`}>
                        编辑
                      </Link>
                      <a style={{ marginLeft: 10 }}>删除</a>
                    </span>
                  )
                }
              }
            ]}
          />
        </Col>
      </Row>
      <Modal
        title="选择活动"
        open={isModalOpen}
        maskClosable={false}
        width={750}
        destroyOnClose
        footer={null}
        onCancel={() => setIsModalOpen(false)}
      >
        <Divider />

        <div className="active-list">
          {activeList.map((item, index) => (
            <div
              key={index}
              className={selectedIndex === index ? 'selected' : ''}
              onClick={() => setSelectedIndex(index)}
            >
              <span>
                <span className="icon">{item.icon}</span>
                <span>{item.title}</span>
              </span>
            </div>
          ))}
        </div>
        <Flex justify="center" align="center" style={{ marginTop: 30 }}>
          <Button
            type="primary"
            size="large"
            style={{ padding: '0 40px' }}
            onClick={() => navigate('/admin/market/addActivaty')}
          >
            新建活动
          </Button>
        </Flex>
      </Modal>
    </>
  )
}
